<template>
  <!-- 筛选区域 -->
  <div class="sub-filter">
    <!-- 品牌 -->
    <!-- 1. 品牌 （固定的）-->
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <a
          href="javascript:;"
          v-for="brand in subCategoryData.brands"
          :key="brand.id"
          :class="{ active: brand.selected }"
          @click="setBrand(brand)"
          >{{ brand.name }}</a
        >
      </div>
    </div>
    <!-- 规格（动态多个） -->
    <!-- 2. 分类商品规格属性 （不固定的，根据商品自身属性决定）-->
    <div
      class="item"
      v-for="item in subCategoryData.saleProperties"
      :key="item.id"
    >
      <div class="head">{{ item.name }}：</div>
      <div class="body">
        <a
          href="javascript:;"
          v-for="i in item.properties"
          :key="i.id"
          :class="{ active: i.selected }"
          @click="setPrd(i, item)"
          >{{ i.name }}</a
        >
      </div>
    </div>
  </div>
</template>

<script>
import { inject } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    const filterParams = inject('filterParams')
    const subCategoryData = inject('subCategoryData')
    // 处理选中品牌
    const setBrand = (brand) => {
      subCategoryData.value.brands.forEach(item => {
        item.selected = false
      })
      brand.selected = true
      filterParams.value.brandId = brand.id
    }
    // 商品选中商品规格
    /**
     * current 当前点击
     * prop 商品规格数据
     */
    const setPrd = (current, prop) => {
      if (current.selected) return
      prop.properties.forEach(item => {
        item.selected = false
      })
      current.selected = true
      // 添加规格过滤条件
      const index = filterParams.value.attrs.findIndex(item => item.group === prop.name)
      // 一个规格下只能添加一个条件=》删除上次选择
      if (index > -1) {
        filterParams.value.attrs.splice(index, 1)
      }
      if (current.id !== null) {
        // 添加新选择的条件
        filterParams.value.attrs.push({
          groupName: prop.name,
          propertyName: current.name
        })
      }
    }
    return { subCategoryData, setBrand, setPrd }
  }
}
</script>

<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    padding: 10px 0;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        display: inline-block;
        margin-right: 36px;
        margin-bottom: 20px;
        transition: all 0.3s;
        border: 1px solid #eee;
        padding: 6px;
        &.active,
        &:hover {
          color: @xtxColor;
          border-color: @xtxColor;
        }
      }
    }
  }
}
</style>
